package com.yanboo.common.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.lang.management.ManagementFactory;

@Slf4j
@Service
public class UidGenerator implements IdentifierGenerator {

    public UidGenerator(){
        WORKER_ID = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr())+Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
        long datacenterIdBits = 5L;
        long maxDatacenterId = ~(-1L << datacenterIdBits);
        long maxWorkerId = ~(-1L << 5L);
        DATACENTER_ID= IdUtil.getDataCenterId(maxDatacenterId);
        WORKER_ID=IdUtil.getWorkerId(DATACENTER_ID,maxWorkerId);
        snowflake = IdUtil.createSnowflake(WORKER_ID, DATACENTER_ID);
        log.info("当前机器的workId:{}", WORKER_ID);
    }
    /**
     * 终端ID
     */
    private  long WORKER_ID ; ;

    /**
     * 数据中心id
     */
    private  long DATACENTER_ID;

    private Snowflake snowflake;

//    @PostConstruct
//    public void init() {
//
//    }

    public synchronized long snowflakeId() {
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }


    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object)
            throws HibernateException {
        return snowflakeId(WORKER_ID, DATACENTER_ID);
    }
}
